<?php

namespace core\middleware\admin;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\bll\SyscnfSafe as BllSyscnfSafe;
use Exception;
use Shopwwi\LaravelCache\Cache;

/**
 * 安全拦截器
 */
class SaveIntercept implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        if (strtolower(explode('/', get_controller())[0]) == 'admin') {

            $frame_syscnf_save = Cache::get('frame_syscnf_safe');
            if (!$frame_syscnf_save) {
                $BllSyscnfSafe     = new BllSyscnfSafe();
                $frame_syscnf_safe = $BllSyscnfSafe->find();
                Cache::add('frame_syscnf_safe', $frame_syscnf_safe);
            }

            if ($frame_syscnf_save) {
                $ip = request()->getRealIp();
                if ($frame_syscnf_save['whitelist'] != '') {
                    $whitelists = explode(',', $frame_syscnf_save['whitelist']);
                    if (!in_array($ip, $whitelists)) {
                        throw new Exception('您的IP被限制登录');
                    }
                }
                if ($frame_syscnf_save['blacklist'] != '') {
                    $blacklists = explode(',', $frame_syscnf_save['blacklist']);
                    if (in_array($ip, $blacklists)) {
                        throw new Exception('您的IP被限制登录');
                    }
                }
            }
        }
        return $handler($request);
    }
}
